package com.vitabuybuy.tv.ui.home.live.viewmodel

import android.view.View
import androidx.databinding.ObservableArrayList
import com.library.common.base.BaseViewModel
import com.library.common.base.MessageModel
import com.library.common.ext.rxHttpRequest
import com.library.common.net.error.msg
import com.library.common.net.loadingtype.LoadingType
import com.library.common.toast.XToast
import com.vitabuybuy.tv.BR
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.dto.LiveListDto
import com.vitabuybuy.tv.inter.OnItemLiveClickListener
import com.vitabuybuy.tv.network.AddressRepository
import com.vitabuybuy.tv.network.CouponCenterRepository
import com.vitabuybuy.tv.network.LiveRepository
import me.tatarka.bindingcollectionadapter2.ItemBinding
import me.tatarka.bindingcollectionadapter2.OnItemBind

class LiveAreaViewModel : BaseViewModel() {

    private val itemOnClickListener = object : OnItemLiveClickListener {
        override fun onItemClick(item: LiveListDto, position: Int) {
            defUI.msgEvent.postValue(MessageModel(2, obj = item))
        }
    }

    val livelist = ObservableArrayList<LiveListDto>()

    //网格布局的adapter绑定
    val liveBinding: OnItemBind<LiveListDto> =
        OnItemBind { itemBinding: ItemBinding<Any>, position: Int, item: LiveListDto ->
            itemBinding.set(BR.itemBean, R.layout.item_list_live).bindExtra(BR.position, position)
                .bindExtra(BR.listenner, itemOnClickListener)
        }

    fun getLiveList(
        categoryId: Int,
        sort: String,
        regionId: Int,
        keywork: String?,
        pageNumber: Int
    ) {
        val params = HashMap<String, Any>()
        if (categoryId != -1) params["category"] = mapOf(Pair("category", categoryId))
        if (regionId != -1) params["region"] = mapOf(Pair("id", regionId))
        if (!keywork.isNullOrEmpty()) params["keywork"] = keywork
        rxHttpRequest {
            onRequest = {
                val it = LiveRepository.getLiveList(params, sort, pageNumber).await()
                if (pageNumber == 1) {
                    livelist.clear()
                }
                livelist.addAll(it)
                if (livelist.isEmpty()) {
                    statusView.set(LoadingType.SHOW_EMPTY)
                }else{
                    statusView.set(LoadingType.SHOW_CONTENT)
                }
                defUI.msgEvent.postValue(MessageModel(1, arg1 = it.size))
            }
            onError = {
                XToast.normal(it.msg)
            }
            isLoadingType = true
            isRefresh = pageNumber == 1
        }
    }

    fun getRegionList(regionId: Int?) {
        rxHttpRequest {
            onRequest = {
                val it = AddressRepository.getRegionList(regionId).await()
                defUI.msgEvent.postValue(MessageModel(3, obj = it))
            }
            onError = {
                XToast.normal(it.msg)
            }
            isShowDialogRequest = true
        }
    }
}
